package yz.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;

public class zookeeperDemo7 {
    public static void main(String[] args) throws InterruptedException, KeeperException, IOException {
        ZooKeeper zooKeeper = new ZooKeeper("master:2181,node1:2181,node2:2181", 15000, new Watcher() {
            //对于接口对象创建时，要实现抽象函数
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println("连接正在连接。。。连接成功");
            }
        });

        //删除所有节点，可以使用递归的方式
        String path = "/api";
        deleteAll(path,zooKeeper,path);
        zooKeeper.close();


    }
    public static void deleteAll(String path,ZooKeeper zooKeeper,String startPath) throws InterruptedException, KeeperException {
        //path如果存在
        Stat exists = zooKeeper.exists(path, false);
        if (exists != null){
            if (exists.getNumChildren() == 0){
                System.out.println("删除子节点："+path);
                zooKeeper.delete(path,-1);
            }
            else {
                List<String> children = zooKeeper.getChildren(path, false);
                for (String child : children) {
                    String paths=path+"/"+child;
                    deleteAll(paths,zooKeeper,startPath);
                }
                //删除子节点，向上回溯
                if (!(startPath.equals(path))){
                    deleteAll(path,zooKeeper,startPath);
                }
                else{
                    System.out.println("删除子节点："+path);
                    zooKeeper.delete(path,-1);
                }
            }
        }
    }
}
